package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApUnLikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApUnlikesBehaviorService;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnLikesBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
            //1.检查参数
            if(dto == null || dto.getArticleId() == null){
                CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数有误");
            }
            // 查询行为实体  如何获取行为实体 根据当前登录的用户Id  获取行为实体对象
            ApUser apUser = AppThreadLocalUtils.getUser();
            ApBehaviorEntry entry =  apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
            if(entry==null){
                CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"无法记录不喜欢行为");
            }
            // 查询是否点过赞 如果点过 并且是 取消点赞
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()).eq(ApUnlikesBehavior::getEntryId, entry.getId()));
            //2. 不喜欢或取消不喜欢 0 不喜欢  1 取消不喜欢
            if(apUnlikesBehavior == null && dto.getType() == 0){
                // 记录
                apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setEntryId(entry.getId());
                apUnlikesBehavior.setType(dto.getType());
                apUnlikesBehavior.setCreatedTime(new Date());
                this.save(apUnlikesBehavior);
            }else if(apUnlikesBehavior !=null && dto.getType() == 1){
                // 取消不喜欢
                apUnlikesBehavior.setType(dto.getType());
                updateById(apUnlikesBehavior);
            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
}
